package com.hjy.cabinet.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hjy.cabinet.db.domain.UserSyncVo;

import java.util.List;

public class UserDataInstance {
    private static UserDataInstance instance;

    private UserbaseHelper dbHelper;
    private SQLiteDatabase db;

    private UserDataInstance() {
    }

    public static UserDataInstance getInstance() {
        if (instance == null) {
            synchronized (UserDataInstance.class) {
                if (instance == null) {
                    instance = new UserDataInstance();
                }
            }
        }
        return instance;
    }

    // 打开数据库
    private void open() {
        db = dbHelper.getWritableDatabase();
    }

    // 关闭数据库
    private void close() {
        if (db != null && db.isOpen()) {
            db.close();
        }
    }

    // 查询用户名和密码是否存在
    public boolean isUserExist(String username, String password) {
        Cursor cursor = null;
        try {
            open();
            String[] columns = {"id"};
            String selection = "username = ? AND password = ? AND deleteStatus = 0";
            String[] selectionArgs = {username, password};

            cursor = db.query("users", columns, selection, selectionArgs, null, null, null);
            return cursor.getCount() > 0;
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error checking if user exists: " + e.getMessage(), e);
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
    }

    public UserSyncVo getAccountUsers(String username, String password) {
        Cursor cursor = null;
        UserSyncVo user = null;
        try {
            if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
                Log.w("DatabaseWarning", "Invalid username or password: null or empty");
                return null;
            }

            open();
            String[] columns = {
                    "id", "fullName", "userName", "sex", "tel",
                    "orgName", "ids", "idCard"
            };
            String selection = "username = ? AND password = ? AND deleteStatus = 0";
            String[] selectionArgs = {username, password};

            cursor = db.query("users", columns, selection, selectionArgs, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                user = new UserSyncVo();
                user.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                user.setFullName(cursor.getString(cursor.getColumnIndexOrThrow("fullName")));
                user.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("userName")));
                user.setSex(cursor.getString(cursor.getColumnIndexOrThrow("sex")));
                user.setTel(cursor.getString(cursor.getColumnIndexOrThrow("tel")));
                user.setOrgName(cursor.getString(cursor.getColumnIndexOrThrow("orgName")));
                user.setIds(cursor.getString(cursor.getColumnIndexOrThrow("ids")));
                user.setIdCard(cursor.getString(cursor.getColumnIndexOrThrow("idCard")));
            }

            return user;
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error retrieving account users: " + e.getMessage(), e);
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
    }

    public long insertUser(UserSyncVo userVo) {
        open();
        try {
            ContentValues values = new ContentValues();
            values.put("id", userVo.getId());
            values.put("fullName", userVo.getFullName());
            values.put("userName", userVo.getUserName());
            values.put("password", userVo.getPassword());
            values.put("roleId", userVo.getRoleId());
            values.put("sex", userVo.getSex());
            values.put("tel", userVo.getTel());
            values.put("orgId", userVo.getOrgId());
            values.put("deleteStatus", userVo.getDeleteStatus() ? 1 : 0);
            values.put("status", userVo.getStatus() ? 1 : 0);
            values.put("avatar", userVo.getAvatar());
            values.put("updateBy", userVo.getUpdateBy());
            values.put("updateUserName", userVo.getUpdateUserName());
            values.put("updateTime", userVo.getUpdateTime());
            values.put("orgName", userVo.getOrgName());
            values.put("ids", userVo.getIds());
            values.put("oldPassword", userVo.getOldPassword());
            values.put("newPassword", userVo.getNewPassword());
            values.put("idCard", userVo.getIdCard());

            return db.insert("users", null, values);
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error inserting user: " + e.getMessage(), e);
            throw e;
        } finally {
            close();
        }
    }

    public void deleteUser(String userId) {
        open();
        try {
            UserSyncVo dbUser = getUserById(userId);
            if (dbUser != null) {
                dbUser.setStatus(true);
                updateUser(dbUser);
            }
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error deleting user: " + e.getMessage(), e);
            throw e;
        } finally {
            close();
        }
    }

    public void deleteAllUsers() {
        open();
        try {
            db.delete("users", null, null);
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error deleting all users: " + e.getMessage(), e);
        } finally {
            close();
        }
    }

    public int updateUser(UserSyncVo userVo) {
        open();
        try {
            ContentValues values = new ContentValues();
            values.put("id", userVo.getId());
            values.put("fullName", userVo.getFullName());
            values.put("userName", userVo.getUserName());
            values.put("password", userVo.getPassword());
            values.put("roleId", userVo.getRoleId());
            values.put("sex", userVo.getSex());
            values.put("tel", userVo.getTel());
            values.put("orgId", userVo.getOrgId());
            values.put("status", userVo.getStatus() ? 1 : 0);
            values.put("avatar", userVo.getAvatar());
            values.put("updateBy", userVo.getUpdateBy());
            values.put("updateUserName", userVo.getUpdateUserName());
            values.put("updateTime", userVo.getUpdateTime());
            values.put("orgName", userVo.getOrgName());
            values.put("ids", userVo.getIds());
            values.put("oldPassword", userVo.getOldPassword());
            values.put("newPassword", userVo.getNewPassword());
            values.put("idCard", userVo.getIdCard());
            values.put("deleteStatus", userVo.getDeleteStatus() ? 1 : 0);

            String selection = "id = ?";
            String[] selectionArgs = {String.valueOf(userVo.getId())};
            return db.update("users", values, selection, selectionArgs);
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error updating user: " + e.getMessage(), e);
            throw e;
        } finally {
            close();
        }
    }

    public UserSyncVo getUserById(String userId) {
        open();
        UserSyncVo userVo = null;
        Cursor cursor = null;
        try {
            String[] projection = {
                    "id", "fullName", "userName", "password", "roleId",
                    "sex", "tel", "orgId", "status", "avatar",
                    "updateBy", "updateUserName", "updateTime", "orgName",
                    "ids", "oldPassword", "newPassword", "idCard"
            };

            String selection = "id = ? AND deleteStatus = 0";
            String[] selectionArgs = {userId};
            cursor = db.query("users", projection, selection, selectionArgs, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                userVo = new UserSyncVo();
                userVo.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                userVo.setFullName(cursor.getString(cursor.getColumnIndexOrThrow("fullName")));
                userVo.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("userName")));
                userVo.setPassword(cursor.getString(cursor.getColumnIndexOrThrow("password")));
                userVo.setRoleId(cursor.getString(cursor.getColumnIndexOrThrow("roleId")));
                userVo.setSex(cursor.getString(cursor.getColumnIndexOrThrow("sex")));
                userVo.setTel(cursor.getString(cursor.getColumnIndexOrThrow("tel")));
                userVo.setOrgId(cursor.getInt(cursor.getColumnIndexOrThrow("orgId")));
                userVo.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow("status")) == 1);
                userVo.setAvatar(cursor.getString(cursor.getColumnIndexOrThrow("avatar")));
                userVo.setUpdateBy(cursor.getInt(cursor.getColumnIndexOrThrow("updateBy")));
                userVo.setUpdateUserName(cursor.getString(cursor.getColumnIndexOrThrow("updateUserName")));
                userVo.setUpdateTime(cursor.getLong(cursor.getColumnIndexOrThrow("updateTime")));
                userVo.setOrgName(cursor.getString(cursor.getColumnIndexOrThrow("orgName")));
                userVo.setIds(cursor.getString(cursor.getColumnIndexOrThrow("ids")));
                userVo.setOldPassword(cursor.getString(cursor.getColumnIndexOrThrow("oldPassword")));
                userVo.setNewPassword(cursor.getString(cursor.getColumnIndexOrThrow("newPassword")));
                userVo.setIdCard(cursor.getString(cursor.getColumnIndexOrThrow("idCard")));
            }
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error retrieving user by ID: " + e.getMessage(), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
        return userVo;
    }

    public List<UserSyncVo> getAllUsers() {
        try {
            return dbHelper.getAllUsers();
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error retrieving all users: " + e.getMessage(), e);
            return null;
        }
    }

    public UserSyncVo getUserBySyncId(String userId) {
        open();
        UserSyncVo userVo = null;
        Cursor cursor = null;
        try {
            String[] projection = {
                    "id", "fullName", "userName", "password", "roleId",
                    "sex", "tel", "orgId", "status", "avatar",
                    "updateBy", "updateUserName", "updateTime", "orgName",
                    "ids", "oldPassword", "newPassword", "idCard"
            };

            String selection = "id = ?";
            String[] selectionArgs = {userId};
            cursor = db.query("users", projection, selection, selectionArgs, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                userVo = new UserSyncVo();
                userVo.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                userVo.setFullName(cursor.getString(cursor.getColumnIndexOrThrow("fullName")));
                userVo.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("userName")));
                userVo.setPassword(cursor.getString(cursor.getColumnIndexOrThrow("password")));
                userVo.setRoleId(cursor.getString(cursor.getColumnIndexOrThrow("roleId")));
                userVo.setSex(cursor.getString(cursor.getColumnIndexOrThrow("sex")));
                userVo.setTel(cursor.getString(cursor.getColumnIndexOrThrow("tel")));
                userVo.setOrgId(cursor.getInt(cursor.getColumnIndexOrThrow("orgId")));
                userVo.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow("status")) == 1);
                userVo.setAvatar(cursor.getString(cursor.getColumnIndexOrThrow("avatar")));
                userVo.setUpdateBy(cursor.getInt(cursor.getColumnIndexOrThrow("updateBy")));
                userVo.setUpdateUserName(cursor.getString(cursor.getColumnIndexOrThrow("updateUserName")));
                userVo.setUpdateTime(cursor.getLong(cursor.getColumnIndexOrThrow("updateTime")));
                userVo.setOrgName(cursor.getString(cursor.getColumnIndexOrThrow("orgName")));
                userVo.setIds(cursor.getString(cursor.getColumnIndexOrThrow("ids")));
                userVo.setOldPassword(cursor.getString(cursor.getColumnIndexOrThrow("oldPassword")));
                userVo.setNewPassword(cursor.getString(cursor.getColumnIndexOrThrow("newPassword")));
                userVo.setIdCard(cursor.getString(cursor.getColumnIndexOrThrow("idCard")));
            }
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error retrieving user by sync ID: " + e.getMessage(), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
        return userVo;
    }

    public List<UserSyncVo> getUsersPage(String fullName, int offset, int limit) {
        try {
            return dbHelper.getUsersPage(fullName, offset, limit);
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error retrieving users page: " + e.getMessage(), e);
            return null;
        }
    }

    public void setDbHelper(UserbaseHelper dbHelper) {
        this.dbHelper = dbHelper;
    }

    public UserSyncVo getICardUsers(String cardValue) {
        Cursor cursor = null;
        UserSyncVo user = null;
        try {
            if (cardValue == null || cardValue.isEmpty()) {
                Log.w("DatabaseWarning", "Invalid card value: null or empty");
                return null;
            }

            open();
            String[] columns = {
                    "id", "fullName", "userName", "sex", "tel",
                    "orgName", "ids", "idCard"
            };

            String selection = "idCard = ? AND deleteStatus = 0 AND idCard IS NOT NULL";
            String[] selectionArgs = {cardValue};

            cursor = db.query("users", columns, selection, selectionArgs, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                user = new UserSyncVo();
                user.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                user.setFullName(cursor.getString(cursor.getColumnIndexOrThrow("fullName")));
                user.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("userName")));
                user.setSex(cursor.getString(cursor.getColumnIndexOrThrow("sex")));
                user.setTel(cursor.getString(cursor.getColumnIndexOrThrow("tel")));
                user.setOrgName(cursor.getString(cursor.getColumnIndexOrThrow("orgName")));
                user.setIds(cursor.getString(cursor.getColumnIndexOrThrow("ids")));
                user.setIdCard(cursor.getString(cursor.getColumnIndexOrThrow("idCard")));
            }

            return user;
        } catch (Exception e) {
            Log.e("UserDataInstance", "Error checking card value: " + e.getMessage(), e);
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
    }
}